<template>
  <div>
    <el-row>
      <el-col style="margin-top: 30px">
        <el-input
          v-model="search"
          style="width: 240px"
          placeholder="请输入药盒方案名"
        />
        <el-button style="margin-left: 20px" type="primary">搜索</el-button>
        <el-button style="margin-left: 20px" type="primary" @click="add"
          >添加药盒方案</el-button
        >
      </el-col>

      <el-col style="margin-top: 10px">
        <el-table
          class="box-table"
          :data="reactiveDrugWarehouseMRS"
          :stripe="true"
          :border="true"
          :fit="true"
        >
          <el-table-column
            prop="name"
            label="药盒配药方案名称"
            width="auto"
            align="center"
            header-align="center"
          >
          </el-table-column>

          <el-table-column
            fixed="right"
            label="操作"
            align="center"
            width="auto"
          >
            <template #default="scope">
              <el-button
                link
                type="primary"
                size="small"
                @click="detail(scope.row)"
                >详情/编辑</el-button
              >
              <el-button
                link
                type="primary"
                size="small"
                style="color: red"
                @click="delBerbak(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-col>

      <el-col style="margin: 0 auto">
        <el-card>
          <div class="block">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="pageSize"
              :total="Total"
            >
            </el-pagination>
          </div>
        </el-card>
      </el-col>

      <!-- 详情 -->
      <el-dialog title="药盒配药详情" v-model="dialogFormVisible" width="40%">
        <div style="margin-top: 20px; height: 30px">
          <span
            >药盒方案名:
            <el-input
              v-model="edit_name"
              style="width: 150px; margin-left: 100px"
              placeholder="请输入药盒方案名"
          /></span>
        </div>
        <el-table
          class="box-table"
          :data="msg_info"
          :stripe="true"
          :border="true"
          :fit="true"
          style="margin-top: 20px"
        >
          <el-table-column
            prop="serialno"
            label="药仓"
            width="auto"
            align="center"
            header-align="center"
          >
          </el-table-column>
          <el-table-column
            prop="drugWarehousemrname"
            label="药仓方案名"
            width="auto"
            align="center"
            header-align="center"
          >
            <template #default="scope">
              <el-select
                v-model="scope.row.drugWarehousemrname"
                placeholder="请选择药仓方案"
              >
                <el-option
                  v-for="option in yaocang_options"
                  :key="option.id"
                  :label="option.name"
                  :value="option.id"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
        </el-table>
        <el-button link type="primary" size="small" @click="baocun_edit()"
          >保存</el-button
        >
      </el-dialog>

      <!-- 添加药盒 -->
      <el-dialog
        v-model="dialogVisible_add"
        title="添加整体药盒配药方案"
        width="40%"
        :before-close="handleClose"
      >
        <div style="margin-top: 20px; height: 30px">
          <span
            >药盒方案名:
            <el-input
              v-model="name"
              style="width: 150px; margin-left: 100px"
              placeholder="请输入药盒方案名"
          /></span>
        </div>
        <div style="margin-top: 20px; height: 30px">
          <span
            >请选择启用药仓数量
            <el-select
              v-model="itemCount"
              placeholder="药仓数量"
              size="large"
              style="width: 150px; margin-left: 50px"
              @change="itemCount_change"
            >
              <el-option
                v-for="item in options_itemCount"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              /> </el-select
          ></span>
        </div>

        <el-table
          class="box-table"
          :data="add_yaocang"
          :stripe="true"
          :border="true"
          :fit="true"
          style="margin-top: 20px"
        >
          <el-table-column
            prop="serialno"
            label="药仓"
            width="auto"
            align="center"
            header-align="center"
          >
          </el-table-column>

          <el-table-column label="药仓方案" align="center" width="auto">
            <template #default="scope">
              <el-select
                v-model="scope.row.drugWarehousemrid"
                placeholder="请选择药仓方案"
              >
                <el-option
                  v-for="option in yaocang_options"
                  :key="option.id"
                  :label="option.name"
                  :value="option.id"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>

          <!-- <el-table-column
            fixed="right"
            label="操作"
            align="center"
            width="auto"
          >
            <template #default="scope">
              <el-button
                link
                type="primary"
                size="small"
                @click="detail(scope.row)"
                >详情/编辑</el-button
              >
            </template>
          </el-table-column> -->
        </el-table>
        <el-button
          style="width: 20%; margin-left: 20%; margin-top: 20px"
          type="primary"
          @click="baocun_add"
          >保存</el-button
        >
      </el-dialog>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, toRaw, onMounted, onBeforeUnmount } from "vue";
import apiService from "@/services/apiService";
import { v4 as uuidv4 } from "uuid";
import { Delete } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import dayjs from "dayjs";
import { getToken } from "@/utils/auth";
import { message } from "@/utils/message";

//表格数据
const currentPage = ref(1); // 当前页数
const pageSize = ref(10); // 每页条数
const Total = ref<number>(1); //总条数
const search = ref("");

const reactiveDrugWarehouseMRS = reactive([
  // {
  //   id: "1",
  //   name: "测试1",
  //   remark: "测试备注",
  //   drugWarehousemrs: [
  //     {
  //       serialno: "药仓1",
  //       drugWarehousemr: "药仓方案1",
  //       remark: "测试"
  //     },
  //     {
  //       serialno: "药仓2",
  //       drugWarehousemr: "药仓方案2",
  //       remark: "测试"
  //     }
  //   ]
  // },
  // {
  //   id: "22",
  //   name: "测试",
  //   remark: "测试备注",
  //   drugWarehousemrs: [
  //     {
  //       serialno: "药仓1",
  //       drugWarehousemr: "药仓方案1",
  //       remark: "测试"
  //     },
  //     {
  //       serialno: "药仓2",
  //       drugWarehousemr: "药仓方案2",
  //       remark: "测试"
  //     }
  //   ]
  // }
]);
//获取当前药盒
const GetList = () => {
  const params = {
    msgid: "PagingFindDeviceMR",
    token: getToken().accessToken,
    seq: uuidv4(),
    body: {
      pageno: currentPage.value,
      pagesize: pageSize.value,
      userid: null
    }
  };

  apiService
    .post("", params)
    .then((res: any) => {
      // console.log("获取当前药盒方案:", res.data);
      // 清空现有数据
      reactiveDrugWarehouseMRS.splice(0);
      reactiveDrugWarehouseMRS.push(...res.data.body.devicemrs);
      Total.value = res.data.body.total;
    })
    .catch(error => {
      console.error("Error fetching data:", error);
    });
};

// 监听页码变化
const handleCurrentChange = val => {
  currentPage.value = val;
  GetList();
};

// 监听每页条数变化
const handleSizeChange = val => {
  pageSize.value = val;
};

//添加药盒方案
const dialogVisible_add = ref(false);
const add_yaocang = ref<any>([]);
// 定义需要创建药仓的数量
const itemCount = ref<any>();
const options_itemCount = reactive([]);

const itemCount_change = () => {
  add_yaocang.value = [];
  for (let i = 1; i <= itemCount.value; i++) {
    add_yaocang.value.push({
      serialno: i,
      drugWarehousemrid: ""
    });
  }
};
//获取当前药仓方案
const yaocang_options = reactive([]);
const Danyi_Arr = () => {
  const params = {
    msgid: "PagingFindDrugWarehouseMR",
    token: getToken().accessToken,
    seq: uuidv4(),
    body: {
      pageno: 1,
      pagesize: 1000,
      userid: null
    }
  };
  apiService
    .post("", params)
    .then((res: any) => {
      // console.log("当前单一药仓方案：", res.data);

      // 清空现有数据
      yaocang_options.splice(0);
      if (res.data.code == 200) {
        res.data.body.drugwarehousemrs.forEach(item => {
          yaocang_options.push({
            id: item.id,
            name: item.name
          });
        });
      }

      // console.log("当前药仓方案:", yaocang_options);
    })
    .catch(error => {
      console.error("Error fetching data:", error);
    });
};
//新增按钮
const add = () => {
  dialogVisible_add.value = true;
};
const name = ref("");
const baocun_add = () => {
  if (add_yaocang.value != "" && itemCount.value != "") {
    const params = {
      msgid: "InsertDeviceMR",
      token: getToken().accessToken,
      seq: uuidv4(),
      body: {
        name: name.value,
        devicedrugwarehousemrs: add_yaocang.value
      }
    };
    apiService
      .post("", params)
      .then((res: any) => {
        // console.log("保存药盒方案：", res.data);
        if (res.data.code == 200) {
          message("新增完成", { type: "success" });
          dialogVisible_add.value = false;
          GetList();
          add_yaocang.value = [];
          name.value = "";
          // 定义需要创建药仓的数量
          itemCount.value = "";
        }
        // console.log("当前药仓方案:", add_yaocang.value);
      })
      .catch(error => {
        console.error("Error fetching data:", error);
      });
  } else {
    message("请填写完整信息", { type: "error" });
  }
};

//删除
const delBerbak = (row: any) => {
  // console.log(row.id);

  ElMessageBox.confirm("确认删除?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      const params = {
        msgid: "RemoveDeviceMRByID",
        token: getToken().accessToken,
        seq: uuidv4(),
        body: {
          id: row.id
        }
      };
      apiService.post("", params).then((res: any) => {
        // console.log(res);
        if (res.data.code == 200) {
          ElMessage({
            type: "success",
            message: "删除成功"
          });
          GetList();
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除"
      });
    });
};

//详情
const dialogFormVisible = ref(false);
const msg_info = ref<any>([]);

const detail = (row: any) => {
  console.log("详情", row);
  msg_info.value = row.drugWarehousemrs;
  edit_name.value = row.name;
  edit_id.value = row.id;
  user_id.value = row.userid;
  dialogFormVisible.value = true;
};
//修改
const edit_name = ref<any>("");
const edit_id = ref<any>("");
const user_id = ref<any>("");
//保存
const baocun_edit = () => {
  if (edit_name.value != "" && msg_info.value != []) {
    const params = {
      msgid: "UpdateDeviceMRByID",
      token: getToken().accessToken,
      seq: uuidv4(),
      body: {
        id: edit_id.value,
        userid: user_id.value,
        name: edit_name.value,
        devicedrugwarehousemrs: msg_info.value
      }
    };
    apiService.post("", params).then((res: any) => {
      console.log("修改药盒方案：", res.data);
      if (res.data.code == 200) {
        message("修改完成", { type: "success" });
        GetList();
        dialogFormVisible.value = false;
      }
      // console.log("当前药仓方案:", add_yaocang.value);
    });
  } else {
    message("请填写完整信息", { type: "error" });
  }
};

//关闭弹窗
const handleClose = (done: () => void) => {
  done();
  add_yaocang.value = [];
  name.value = "";
  // 定义需要创建药仓的数量
  itemCount.value = "";
  console.log("关闭");
};

onMounted(async () => {
  GetList();
  Danyi_Arr();

  for (let i = 1; i <= 12; i++) {
    options_itemCount.push({
      value: i.toString(),
      label: i.toString()
    });
  }
});
</script>

<style lang="scss" scoped>
:deep(.el-select--large .el-select__wrapper) {
  min-height: 0px;
}
.active-button {
  background-color: #409eff; /* 设置按钮激活时的背景颜色 */
  color: white; /* 设置按钮激活时的文字颜色 */
}
</style>
